class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int minSum = nums[0], maxSum = nums[0];
        int m = nums.size();
        int minPre = nums[0], maxPre = nums[0], all = nums[0];
        for(int i = 1; i < m; ++i)
        {
            all += nums[i];
            maxPre = max(maxPre + nums[i], nums[i]);
            maxSum = max(maxSum, maxPre);

            minPre = min(minPre + nums[i], nums[i]);
            minSum = min(minSum, minPre);
        }
        return all == minSum ? maxSum : max(maxSum, all - minSum); 
    }
};
